"use client";

import { useState, useEffect, useRef } from "react";
import { useRouter } from "next/navigation";
import { motion } from "framer-motion";
import {
  FiSearch,
  FiFilter,
  FiPlus,
  FiFile,
  FiFolder,
  FiClock,
  FiUser,
  FiMoreVertical,
  FiStar,
  FiEye,
  FiChevronDown,
  FiChevronLeft,
  FiChevronRight,
} from "react-icons/fi";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";

// 模拟文档数据
const mockDocuments = [
  {
    id: "1",
    title: "系统架构设计文档",
    description: "详细描述了系统的整体架构设计和技术选型",
    author: "张三",
    viewableRoles: ["管理员", "技术人员"],
    tags: ["架构", "设计"],
    updatedAt: "2023-10-15 14:30",
    createdAt: "2023-10-10 09:15",
    starred: true,
    viewCount: 156,
  },
  {
    id: "2",
    title: "产品需求规格说明书",
    description: "详细描述了产品功能、用户故事和验收标准",
    author: "李四",
    viewableRoles: ["管理员", "产品经理"],
    tags: ["需求", "产品"],
    updatedAt: "2023-10-14 11:20",
    createdAt: "2023-10-09 15:45",
    starred: false,
    viewCount: 89,
  },
  {
    id: "3",
    title: "季度财务报告",
    description: "第三季度公司财务状况详细报告",
    author: "王五",
    viewableRoles: ["管理员", "财务人员"],
    tags: ["财务", "报告"],
    updatedAt: "2023-10-12 09:15",
    createdAt: "2023-10-08 10:30",
    starred: true,
    viewCount: 42,
  },
  {
    id: "4",
    title: "员工培训计划",
    description: "2023年Q4员工技能提升培训计划",
    author: "赵六",
    viewableRoles: ["管理员", "人事专员"],
    tags: ["培训", "HR"],
    updatedAt: "2023-10-11 16:40",
    createdAt: "2023-10-05 11:20",
    starred: false,
    viewCount: 67,
  },
  {
    id: "5",
    title: "市场营销战略",
    description: "2024年市场拓展及品牌建设战略规划",
    author: "孙七",
    viewableRoles: ["管理员", "市场专员"],
    tags: ["市场", "营销"],
    updatedAt: "2023-10-10 14:20",
    createdAt: "2023-10-03 09:15",
    starred: false,
    viewCount: 108,
  },
];

// 模拟角色数据
const roles = [
  { id: "all", name: "全部角色" },
  { id: "admin", name: "管理员" },
  { id: "tech", name: "技术人员" },
  { id: "product", name: "产品经理" },
  { id: "finance", name: "财务人员" },
  { id: "hr", name: "人事专员" },
  { id: "marketing", name: "市场专员" },
];

export default function DocumentsListPage() {
  const router = useRouter();
  const [documents, setDocuments] = useState([]);
  const [isLoading, setIsLoading] = useState(true);
  const [searchQuery, setSearchQuery] = useState("");
  const [selectedRole, setSelectedRole] = useState("all");
  const [currentView, setCurrentView] = useState("grid");
  const [currentPage, setCurrentPage] = useState(1);
  const [showRoleDropdown, setShowRoleDropdown] = useState(false);
  const roleDropdownRef = useRef(null);
  const itemsPerPage = 10;

  // 用于文档操作的下拉菜单状态
  const [openMenuId, setOpenMenuId] = useState(null);

  // 关闭下拉菜单的点击外部处理函数
  useEffect(() => {
    function handleClickOutside(event) {
      if (
        roleDropdownRef.current &&
        !roleDropdownRef.current.contains(event.target)
      ) {
        setShowRoleDropdown(false);
      }

      if (openMenuId !== null && !event.target.closest(".doc-menu")) {
        setOpenMenuId(null);
      }
    }

    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, [openMenuId]);

  useEffect(() => {
    // 模拟API获取文档列表
    const fetchDocuments = async () => {
      try {
        // 模拟延迟
        await new Promise((resolve) => setTimeout(resolve, 800));

        // 使用模拟数据
        setDocuments(mockDocuments);
      } catch (error) {
        console.error("获取文档列表失败:", error);
      } finally {
        setIsLoading(false);
      }
    };

    fetchDocuments();
  }, []);

  // 筛选文档
  const filteredDocuments = documents.filter((doc) => {
    const matchesSearch =
      doc.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
      doc.description.toLowerCase().includes(searchQuery.toLowerCase());
    const matchesRole =
      selectedRole === "all" ||
      doc.viewableRoles.includes(
        roles.find((r) => r.id === selectedRole)?.name || ""
      );

    return matchesSearch && matchesRole;
  });

  // 分页处理
  const totalPages = Math.ceil(filteredDocuments.length / itemsPerPage);
  const paginatedDocuments = filteredDocuments.slice(
    (currentPage - 1) * itemsPerPage,
    currentPage * itemsPerPage
  );

  const handleCreateDocument = () => {
    // 实际项目中应跳转到创建文档页面
    console.log("创建新文档");
    router.push("/documents/new");
  };

  const handleOpenDocument = (id) => {
    router.push(`/documents/${id}`);
  };

  if (isLoading) {
    return (
      <div className='flex justify-center items-center h-[80vh]'>
        <div className='animate-spin rounded-full h-16 w-16 border-t-2 border-b-2 border-blue-500'></div>
      </div>
    );
  }

  const fadeIn = {
    hidden: { opacity: 0, y: 20 },
    visible: { opacity: 1, y: 0 },
  };

  return (
    <div className='container mx-auto px-4 py-8'>
      <motion.div
        initial='hidden'
        animate='visible'
        variants={fadeIn}
        transition={{ duration: 0.3 }}
      >
        {/* 页面标题和操作区 */}
        <div className='flex justify-between items-center mb-8'>
          <h1 className='text-3xl font-bold text-gray-800 dark:text-white'>
            文档中心
          </h1>
          <Button
            onClick={handleCreateDocument}
            className='bg-blue-500 hover:bg-blue-600 text-white'
          >
            <FiPlus className='mr-2' /> 新建文档
          </Button>
        </div>

        {/* 搜索和筛选区 */}
        <div className='bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-200 dark:border-gray-700 p-4 mb-6'>
          <div className='flex flex-col md:flex-row gap-4'>
            <div className='relative flex-1'>
              <div className='absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none'>
                <FiSearch className='text-gray-400' />
              </div>
              <Input
                type='text'
                placeholder='搜索文档...'
                className='pl-10'
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
              />
            </div>

            {/* 角色选择器 */}
            <div className='w-full md:w-64 relative' ref={roleDropdownRef}>
              <button
                className='w-full flex items-center justify-between px-3 py-2 text-sm border rounded-md shadow-sm bg-white dark:bg-gray-800 border-gray-300 dark:border-gray-600'
                onClick={() => setShowRoleDropdown(!showRoleDropdown)}
              >
                <div className='flex items-center'>
                  <FiFilter className='mr-2' />
                  <span>
                    {roles.find((r) => r.id === selectedRole)?.name ||
                      "选择角色"}
                  </span>
                </div>
                <FiChevronDown
                  className={`transition-transform ${
                    showRoleDropdown ? "rotate-180" : ""
                  }`}
                />
              </button>

              {showRoleDropdown && (
                <div className='absolute z-10 w-full mt-1 bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-600 rounded-md shadow-lg'>
                  <ul className='py-1'>
                    {roles.map((role) => (
                      <li
                        key={role.id}
                        className={`px-3 py-2 text-sm cursor-pointer hover:bg-gray-100 dark:hover:bg-gray-700 ${
                          selectedRole === role.id
                            ? "bg-gray-100 dark:bg-gray-700 font-medium"
                            : ""
                        }`}
                        onClick={() => {
                          setSelectedRole(role.id);
                          setShowRoleDropdown(false);
                        }}
                      >
                        {role.name}
                      </li>
                    ))}
                  </ul>
                </div>
              )}
            </div>

            <div className='flex gap-2'>
              <Button
                variant={currentView === "grid" ? "default" : "outline"}
                size='icon'
                onClick={() => setCurrentView("grid")}
              >
                <FiFolder />
              </Button>
              <Button
                variant={currentView === "list" ? "default" : "outline"}
                size='icon'
                onClick={() => setCurrentView("list")}
              >
                <FiFile />
              </Button>
            </div>
          </div>
        </div>

        {/* 文档列表 */}
        {paginatedDocuments.length === 0 ? (
          <div className='bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-200 dark:border-gray-700 p-8 text-center'>
            <div className='text-gray-500 dark:text-gray-400'>
              <FiFile className='mx-auto h-12 w-12 mb-4' />
              <h3 className='text-lg font-medium mb-2'>没有找到文档</h3>
              <p>尝试调整搜索条件或创建新文档</p>
            </div>
          </div>
        ) : currentView === "grid" ? (
          <div className='grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 mb-8'>
            {paginatedDocuments.map((doc) => (
              <motion.div
                key={doc.id}
                initial={{ opacity: 0 }}
                animate={{ opacity: 1 }}
                transition={{ duration: 0.2 }}
                className='bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-200 dark:border-gray-700 overflow-hidden hover:shadow-md transition-shadow cursor-pointer'
                onClick={() => handleOpenDocument(doc.id)}
              >
                <div className='p-6'>
                  <div className='flex justify-between items-start mb-3'>
                    <h2 className='text-xl font-semibold text-gray-800 dark:text-white line-clamp-1'>
                      {doc.title}
                    </h2>
                    <div className='flex items-center'>
                      {doc.starred && (
                        <FiStar className='text-yellow-400 h-5 w-5' />
                      )}

                      {/* 自定义下拉菜单替代 DropdownMenu */}
                      <div className='relative doc-menu'>
                        <button
                          onClick={(e) => {
                            e.stopPropagation();
                            setOpenMenuId(
                              openMenuId === doc.id ? null : doc.id
                            );
                          }}
                          className='p-1.5 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-full'
                        >
                          <FiMoreVertical />
                        </button>

                        {openMenuId === doc.id && (
                          <div className='absolute right-0 z-10 mt-1 w-48 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-md shadow-lg'>
                            <div className='py-1'>
                              <button
                                className='w-full text-left px-4 py-2 text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700'
                                onClick={(e) => {
                                  e.stopPropagation();
                                  console.log("编辑文档", doc.id);
                                  setOpenMenuId(null);
                                }}
                              >
                                编辑文档
                              </button>
                              <button
                                className='w-full text-left px-4 py-2 text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700'
                                onClick={(e) => {
                                  e.stopPropagation();
                                  console.log("分享文档", doc.id);
                                  setOpenMenuId(null);
                                }}
                              >
                                分享文档
                              </button>
                              <button
                                className='w-full text-left px-4 py-2 text-sm text-red-500 hover:bg-gray-100 dark:hover:bg-gray-700'
                                onClick={(e) => {
                                  e.stopPropagation();
                                  console.log("删除文档", doc.id);
                                  setOpenMenuId(null);
                                }}
                              >
                                删除文档
                              </button>
                            </div>
                          </div>
                        )}
                      </div>
                    </div>
                  </div>

                  <p className='text-gray-600 dark:text-gray-300 text-sm mb-4 line-clamp-2'>
                    {doc.description}
                  </p>

                  <div className='flex flex-wrap gap-2 mb-4'>
                    {doc.tags.map((tag, idx) => (
                      /* 自定义标签替代 Badge */
                      <span
                        key={idx}
                        className='inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-50 text-blue-700 dark:bg-blue-900/30 dark:text-blue-300 border border-blue-200 dark:border-blue-800'
                      >
                        {tag}
                      </span>
                    ))}
                  </div>

                  <div className='flex justify-between text-sm text-gray-500 dark:text-gray-400'>
                    <div className='flex items-center'>
                      <FiUser className='mr-1' /> {doc.author}
                    </div>
                    <div className='flex items-center'>
                      <FiEye className='mr-1' /> {doc.viewCount}
                    </div>
                    <div className='flex items-center'>
                      <FiClock className='mr-1' /> {doc.updatedAt.split(" ")[0]}
                    </div>
                  </div>
                </div>
                <div className='bg-gradient-to-r from-blue-50 to-indigo-50 dark:from-blue-900/20 dark:to-indigo-900/20 py-2 px-4 text-sm'>
                  <span className='font-medium text-gray-700 dark:text-gray-300'>
                    可查看角色: {doc.viewableRoles.join(", ")}
                  </span>
                </div>
              </motion.div>
            ))}
          </div>
        ) : (
          <div className='bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-200 dark:border-gray-700 overflow-hidden mb-8'>
            <table className='w-full'>
              <thead className='bg-gray-50 dark:bg-gray-700'>
                <tr>
                  <th className='px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider'>
                    文档名称
                  </th>
                  <th className='px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider'>
                    可查看角色
                  </th>
                  <th className='px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider'>
                    作者
                  </th>
                  <th className='px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider'>
                    更新时间
                  </th>
                  <th className='px-6 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider'>
                    操作
                  </th>
                </tr>
              </thead>
              <tbody className='divide-y divide-gray-200 dark:divide-gray-700'>
                {paginatedDocuments.map((doc) => (
                  <tr
                    key={doc.id}
                    className='hover:bg-gray-50 dark:hover:bg-gray-700/30 cursor-pointer'
                    onClick={() => handleOpenDocument(doc.id)}
                  >
                    <td className='px-6 py-4'>
                      <div className='flex items-center'>
                        <FiFile className='mr-3 text-blue-500' />
                        <div>
                          <div className='font-medium text-gray-900 dark:text-white flex items-center'>
                            {doc.title}
                            {doc.starred && (
                              <FiStar className='ml-2 text-yellow-400 h-4 w-4' />
                            )}
                          </div>
                          <div className='text-sm text-gray-500 dark:text-gray-400'>
                            {doc.description.substring(0, 60)}...
                          </div>
                        </div>
                      </div>
                    </td>
                    <td className='px-6 py-4 whitespace-nowrap text-sm text-gray-700 dark:text-gray-300'>
                      {doc.viewableRoles.join(", ")}
                    </td>
                    <td className='px-6 py-4 whitespace-nowrap text-sm text-gray-700 dark:text-gray-300'>
                      {doc.author}
                    </td>
                    <td className='px-6 py-4 whitespace-nowrap text-sm text-gray-700 dark:text-gray-300'>
                      {doc.updatedAt}
                    </td>
                    <td className='px-6 py-4 whitespace-nowrap text-right text-sm font-medium'>
                      {/* 自定义下拉菜单 */}
                      <div className='relative doc-menu'>
                        <button
                          onClick={(e) => {
                            e.stopPropagation();
                            setOpenMenuId(
                              openMenuId === doc.id ? null : doc.id
                            );
                          }}
                          className='p-1.5 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-full'
                        >
                          <FiMoreVertical />
                        </button>

                        {openMenuId === doc.id && (
                          <div className='absolute right-0 z-10 mt-1 w-48 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-md shadow-lg'>
                            <div className='py-1'>
                              <button
                                className='w-full text-left px-4 py-2 text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700'
                                onClick={(e) => {
                                  e.stopPropagation();
                                  console.log("编辑文档", doc.id);
                                  setOpenMenuId(null);
                                }}
                              >
                                编辑文档
                              </button>
                              <button
                                className='w-full text-left px-4 py-2 text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700'
                                onClick={(e) => {
                                  e.stopPropagation();
                                  console.log("分享文档", doc.id);
                                  setOpenMenuId(null);
                                }}
                              >
                                分享文档
                              </button>
                              <button
                                className='w-full text-left px-4 py-2 text-sm text-red-500 hover:bg-gray-100 dark:hover:bg-gray-700'
                                onClick={(e) => {
                                  e.stopPropagation();
                                  console.log("删除文档", doc.id);
                                  setOpenMenuId(null);
                                }}
                              >
                                删除文档
                              </button>
                            </div>
                          </div>
                        )}
                      </div>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}

        {/* 自定义分页组件替代 Pagination */}
        {totalPages > 1 && (
          <div className='flex justify-center mt-6'>
            <div className='flex items-center space-x-2'>
              <button
                onClick={() => {
                  if (currentPage > 1) setCurrentPage(currentPage - 1);
                }}
                disabled={currentPage === 1}
                className={`px-3 py-2 rounded-md border ${
                  currentPage === 1
                    ? "opacity-50 cursor-not-allowed"
                    : "hover:bg-gray-100 dark:hover:bg-gray-700"
                } border-gray-300 dark:border-gray-600 flex items-center`}
              >
                <FiChevronLeft size={16} />
                <span className='ml-1'>上一页</span>
              </button>

              <div className='flex items-center space-x-1'>
                {[...Array(totalPages)].map((_, i) => (
                  <button
                    key={i}
                    onClick={() => setCurrentPage(i + 1)}
                    className={`w-9 h-9 flex items-center justify-center rounded-md ${
                      currentPage === i + 1
                        ? "bg-blue-500 text-white"
                        : "hover:bg-gray-100 dark:hover:bg-gray-700 border border-gray-300 dark:border-gray-600"
                    }`}
                  >
                    {i + 1}
                  </button>
                ))}
              </div>

              <button
                onClick={() => {
                  if (currentPage < totalPages) setCurrentPage(currentPage + 1);
                }}
                disabled={currentPage === totalPages}
                className={`px-3 py-2 rounded-md border ${
                  currentPage === totalPages
                    ? "opacity-50 cursor-not-allowed"
                    : "hover:bg-gray-100 dark:hover:bg-gray-700"
                } border-gray-300 dark:border-gray-600 flex items-center`}
              >
                <span className='mr-1'>下一页</span>
                <FiChevronRight size={16} />
              </button>
            </div>
          </div>
        )}
      </motion.div>
    </div>
  );
}
